#! /usr/bin/python
#coding:utf-8
"""
利用淘宝的api知道ip地址的来源地址！
利用urllib和requests 来做测试！
"""

from urllib import urlopen
import json
import sys
import requests

def urllibLocation(ip):
    """
    使用urllib模块；
    """
    url="http://ip.taobao.com/service/getIpInfo.php?ip=%s" % ip
    ip_data=urlopen(url)
    list=json.loads(ip_data.read())    
    ip_data.close()
    ip_status=list['code']

    if ip_status == 0:
        location=list['data']['country']+' '+list['data']['region']+' '+list['data']['city']+' '+list['data']['isp']
        return location
    else:
        print "get ip failure...."
        return "failure"



def requestLocation(ip):
    """
    使用 requests 模块；
    """
    url="http://ip.taobao.com/service/getIpInfo.php?ip=%s" % ip
    ip_data=requests.get(url)
    list=ip_data.json()
    ip_data.close()
    if ip_data.status_code == 200:
        if list['code'] == 0:
            location=list['data']['country']+' '+list['data']['region']+' '+list['data']['city']+' '+list['data']['isp']
            return location
        else:
            print "taobap api code is not 0"
    else:
        print "web status is not 200"



#if __main__ == '__name__':
ip=sys.argv[1]
if len(ip) != 0:
   ip_location=urllibLocation(ip)
   location=requestLocation(ip)
   print "get ip location by urllib : %s" %ip_location
   print "get ip location by requests : %s" %location
else:
   print "please input ipaddress!"     
   sys.exit(1)


